<?php

namespace app\admin\service;

use app\model\PayRecord;
use app\model\RefundRecord;
use app\model\User;
use app\common\Common;
use app\common\Error;
use think\facade\Cache;
use app\model\Applet;
use app\model\Client;
use think\facade\Db;
use think\facade\Queue;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\DataType;

class TiktokService
{
    private $model;
    private $appletModel;
    private $clientModel;
    public function __construct(User $model, Applet $appletModel, Client $clientModel)
    {
        $this->model = $model;
        $this->appletModel = $appletModel;
        $this->clientModel = $clientModel;
    }

    /**
     * 消息通知
     * @param $parameterData
     * access_token 小程序 access_token
     * app_id       小程序id
     * tpl_id       模板id
     * open_id      openid小程序用户id
     * data         用来通知消息模板{ "key1": "value1", "key2": "value2" }
     * page         跳转链接
     * return       { "err_no": 0,"err_tips": ""}
     */
    public function notificationMessage($parameterData)
    {
        $url = 'https://developer.toutiao.com/api/apps/subscribe_notification/developer/v1/notify';
        $result = Common::curlRequest($url, 'POST', json_encode($parameterData));
        return json_decode($result, true);
    }

    /**
     * 获取小程序token
     * @param $uid 用户id
     * return token
     */
    public function getAccessToken($id)
    {
        $redis = Cache::store('redis')->handler();
        $redis->select(8);
        $appletData = $this->getAppletInfo($id);

        $token = $redis->get('douyin_token' . $appletData['id']);
        if (!empty($token)) {
            return $token;
        }
        $token_url = 'https://developer.toutiao.com/api/apps/v2/token';
        //获取抖音token
        $arr = [
            'appid' => $appletData['app_id'],
            'secret' => $appletData['app_secret'],
            'grant_type' => 'client_credential',
        ];
        $data = Common::curlRequest($token_url, 'POST', json_encode($arr));

        $data = json_decode($data, true); //获取token
        if ($data['err_no'] == 0) {
            $token = $data['data']['access_token'];
            $redis->set('douyin_token' . $appletData['id'], $token, $data['data']['expires_in']);
            return $token;
        } else {
            return 0;
        }
    }
    /**
     * 查询任务台任务投稿视频数据（明细）
     * @param $params 数据
     * page 页码
     * limit  条数
     * start_time 开始时间
     * end_time  结束时间
     * billing_date 计费时间
     * client_key  合作的撮合中介的网站应用key
     * douyin_id 主播抖音号
     * third_appid  第三方小程序appid（服务商使用的授权小程序）
     * return {"error": 0,"message": "SUCCESS","results": [ ]}
     * 请求地址文档：https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/server/promote/taskbox/query_task_video_data_daily
     */
    public function getTaskVideoDaily($params)
    {
        if(empty($params['id'])) {
            return ['err' => 0,'msg' => '抖音账户错误','data' => []];
        }
        $appletData = $this->getAppletInfo($params['id']);
        if(empty($appletData) || $appletData['type'] != 2) {
            return ['err' => 1,'msg' => '抖音账户错误'];
        }

        $token = $this->getAccessToken($params['id']);
        if($token == 0) {
            return  ['err' => 1,'msg' => '无法请求到抖音token'];
        }
        if(empty($params['start_time']) || empty($params['end_time']) && !empty($params['billing_date'])) {
            $start_time = strtotime($params['billing_date'] . '00:00:00');
            $end_time = strtotime($params['billing_date'] . '23:59:59');
        } else {
            $start_time = strtotime($params['start_time'] . '00:00:00');
            $end_time = strtotime($params['end_time'] . '23:59:59');
        }

        if($start_time < time() - (90 * 24 * 60 * 60)) {
            return ['err' => 1,'msg' => '搜索时间不能超出90天'];
        }
        // if(($end_time - $start_time) > (30 * 24 * 60 * 60)) {
        //     return ['err' => 1,'msg' => '搜索时间区间不能大于30天'];
        // }
        $token_url = 'https://developer.toutiao.com/api/apps/taskbox/query_task_video_daily_data/';
        $end_time=strtotime($params['billing_date'] .' 23:59:59');
        //获取抖音token
        $arr = [
            'page_no' => $params['page'] ?? 0,
            'page_size' => $params['limit'] ?? 10,
            'appid' => $appletData['app_id'],
            'access_token' => $token,
            'video_publish_start_time' => !empty($end_time) ? $end_time-(30*60*24*60) : strtotime(date('Y-m-d', time()) . '00:00:00'),//视频发布的起始时间，秒级时间戳
            'video_publish_end_time' => !empty($end_time) ? $end_time : strtotime(date('Y-m-d', time()) . '23:59:59'),//视频发布的结束时间，秒级时间戳
            'billing_date' => !empty($params['billing_date']) ? $params['billing_date'] : date('Y-m-d', time()),//计费日期
            'client_key' => isset($params['client_key']) ?trim($params['client_key']):'',//合作的撮合中介的网站应用key
            'douyin_id' => isset($params['douyin_id']) ?trim($params['douyin_id']):'',//主播抖音号
            'third_appid' => isset($params['third_appid']) ?trim($params['third_appid']):'',//第三方小程序appid（服务商使用的授权小程序）
        ];
        $data = Common::curlRequest($token_url, 'POST', json_encode($arr));

        $data = json_decode($data, true); //获取token

        if ($data['error'] == 0) {
            foreach($data['results'] as $key => $val) {
                $data['results'][$key]['TaskId'] = (string)$val['TaskId'];
                $data['results'][$key]['VideoId'] = (string)$val['VideoId'];
                //当日从视频进入小程序产生的交易金额，单位：分
                $data['results'][$key]['GMV1d'] = round($data['results'][$key]['GMV1d'] / 100, 2);
                //从视频进入小程序产生的交易金额中，当日退款金额，单位：分
                $data['results'][$key]['RefundGMV1d'] = round($data['results'][$key]['RefundGMV1d'] / 100, 2);
                //任务关联的当日交易金额，单位：分。
                $data['results'][$key]['BillingGMV1d'] = round($data['results'][$key]['BillingGMV1d'] / 100, 2);
                //任务关联的交易金额中，当日退款金额，单位：分。
                $data['results'][$key]['BillingRefundGMV1d'] = round($data['results'][$key]['BillingRefundGMV1d'] / 100, 2);
                //当日从视频进入小程序产生的广告收入（平台抽成后的开发者可分成收入，未扣除买量消耗），单位：分
                $data['results'][$key]['AdShareCost1d'] = round($data['results'][$key]['AdShareCost1d'] / 100, 2);
                //当日从feed流看到视频，并进入小程序产生的广告收入（平台抽成后的开发者可分成收入，未扣除买量消耗），单位：分
                $data['results'][$key]['FeedAdShareCost1d'] = round($data['results'][$key]['FeedAdShareCost1d'] / 100, 2);
            }
            return ['err' => 0,'data' => !empty($data['results']) ? $data['results'] : []];
        } else {
            return ['err' => 1,'msg' => $data['error'] . ":" . $data['message']];
        }
    }
    /**
     * 查询任务台任务单个任务详情
     * @param $params 数据
     * page 页码
     * limit  条数
     * start_time 开始时间
     * end_time  结束时间
     * task_ids 任务id数组
     * third_appid  第三方小程序appid（服务商使用的授权小程序）
     * return {"error": 0,"message": "SUCCESS","data": [ ]}
     * 请求地址文档：https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/server/promote/taskbox/taskbox-query-task-video-data
     */
    public function getTaskVideoData($params)
    {
        if(empty($params['id'])) {
            return ['err' => 0,'msg' => '抖音账户错误','data' => []];
        }
        $appletData = $this->getAppletInfo($params['id']);
        if(empty($appletData) || $appletData['type'] != 2) {
            return ['err' => 1,'msg' => '抖音账户错误'];
        }

        $token = $this->getAccessToken($params['id']);
        if($token == 0) {
            return  ['err' => 1,'msg' => '无法请求到抖音token'];
        }
        $token_url = 'https://developer.toutiao.com/api/apps/taskbox/query_task_video_data';
        //获取抖音token
        $arr = [
            'page_no' => $params['page'] ?? 0,
            'page_size' => $params['limit'] ?? 10,
            'appid' => $appletData['app_id'],
            'access_token' => $token,
            'video_publish_start_time' => isset($params['start_time']) ? strtotime($params['start_time'] . '00:00:00') : strtotime(date('Y-m-d', time()) . '00:00:00'),//视频发布的起始时间，秒级时间戳
            'video_publish_end_time' => isset($params['end_time']) ? strtotime($params['end_time'] . '23:59:59') : strtotime(date('Y-m-d', time()) . '23:59:59'),//视频发布的结束时间，秒级时间戳
            'task_ids' => isset($params['task_ids']) ? explode(',', $params['task_ids']) : [],
            'third_appid' => $params['third_appid'] ?? '',//第三方小程序appid（服务商使用的授权小程序）
        ];
        $data = Common::curlRequest($token_url, 'POST', json_encode($arr));
        $data = json_decode($data, true); //获取token
        // var_dump($data);
        if ($data['error'] == 0) {
            foreach($data['data'] as $key => $val) {
                $data['data'][$key]['TaskId'] = (string)$val['TaskId'];
                $data['data'][$key]['VideoId'] = (string)$val['VideoId'];
                //从视频进入小程序产生的总交易金额，单位：分
                $data['data'][$key]['GMVTd'] = round($data['data'][$key]['GMVTd'] / 100, 2);
                //从视频进入小程序产生的交易金额中，累计退款金额，单位：分
                $data['data'][$key]['RefundGMVTd'] = round($data['data'][$key]['RefundGMVTd'] / 100, 2);
                //任务关联的交易金额，单位：分。
                $data['data'][$key]['BillingGMVTd'] = round($data['data'][$key]['BillingGMVTd'] / 100, 2);
                //任务关联的交易金额中，累计退款金额，单位：分
                $data['data'][$key]['BillingRefundGMVTd'] = round($data['data'][$key]['BillingRefundGMVTd'] / 100, 2);
                //从视频进入小程序产生的广告收入（平台抽成后的开发者可分成收入，未扣除买量消耗），单位：分
                $data['data'][$key]['AdShareCostTd'] = round($data['data'][$key]['AdShareCostTd'] / 100, 2);
                //从feed流看到视频，并进入小程序产生的广告收入（平台抽成后的开发者可分成收入，未扣除买量消耗），单位：分
                $data['data'][$key]['FeedAdShareCostTd'] = round($data['data'][$key]['FeedAdShareCostTd'] / 100, 2);
            }
            return ['err' => 0,'data' => !empty($data['data']) ? $data['data'] : [] ];
        } else {
            return ['err' => 1,'msg' => $data['error'] . ":" . $data['message']];
        }
    }
    /**
     * 获取小程序配置信息
     * @param $uid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAppletInfo($id)
    {

        $appletData = $this->appletModel->getInfoById($id, 'app_id, name,app_secret,template_id,id,type');

        return $appletData;
    }
    /**
     * 撮合合作商和达人信息列表
     *
     * @param [type] $params
     * @return array
     */
    public function getClientList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where[] = ['status', '=', 1];
        if (!empty($params['name'])) {
            $where[] = ['name', 'like', '%' . $params['name'] . '%'];
        }
        if (!empty($params['type'])) {
            $where[] = ['type', '=',  $params['type'] ];
        }
        $data = $this->clientModel->getPagingDataByWhere($where, $page, $limit, '*');
        return $data;
    }
    /**
    * 撮合合作商和达人信息添加修改
    *
    * @param [type] $params
    * @return true
    */
    public function addClient($params)
    {
        if (empty($params['id'])) {
            $params['created_at'] = time();
        } else {
            $params['updated_at'] = time();
        }
        $id = $this->clientModel->edit($params);

        if (!$id) {
            return false;
        }

        return true;
    }
    /**
     *撮合合作商和达人信息下拉列表
     *
     * @param [type] $params
     * @return array
     */
    public function getClientSelectList($params)
    {
        $where = [];
        if (!empty($params['type'])) {
            $where[] = ['type', '=',  $params['type'] ];
        }
        $where[] = ['status', '=', 1 ];
        $data = $this->clientModel->getDataByWhere($where, 'id, name,dy_key');
        return $data;
    }
    /**
     *撮合合作商和达人信息详情
     *
     * @param [type] $params
     * @return array
     */
    public function getClientDetail($id)
    {
        $data = $this->clientModel->getInfoByWhere(['id' => $id], '*');

        return $data;
    }

    /**
     * 查询任务台任务投稿视频数据（明细）
     * @param $params 数据
     * page 页码
     * limit  条数
     * start_time 开始时间
     * end_time  结束时间
     * billing_date 计费时间
     * client_key  合作的撮合中介的网站应用key
     * douyin_id 主播抖音号
     * third_appid  第三方小程序appid（服务商使用的授权小程序）
     * return {"error": 0,"message": "SUCCESS","results": [ ]}
     * 请求地址文档：https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/server/promote/taskbox/query_task_video_data_daily
     */
    public function getTaskVideoDailyMonth($params)
    {
        if(empty($params['id'])) {
            return ['err' => 0,'msg' => '抖音账户错误','data' => []];
        }
        $appletData = $this->getAppletInfo($params['id']);
        if(empty($appletData) || $appletData['type'] != 2) {
            return ['err' => 1,'msg' => '抖音账户错误'];
        }

        $token = $this->getAccessToken($params['id']);
        if($token == 0) {
            return  ['err' => 1,'msg' => '无法请求到抖音token'];
        }
        $start_time = strtotime($params['start_time'] . '00:00:00');
        $end_time = strtotime($params['end_time'] . '23:59:59');
        if($start_time < time() - (90 * 24 * 60 * 60)) {
            return ['err' => 1,'msg' => '搜索时间不能超出90天'];
        }
        // if(($end_time - $start_time) > (30 * 24 * 60 * 60)) {
        //     return ['err' => 1,'msg' => '搜索时间区间不能大于30天'];
        // }
        $redis = Cache::store('redis')->handler();
        $redis->select(8);
        $listdata = $redis->get('douyin_data_video' . $appletData['id'] . '-' . $start_time . '-' . $end_time . '-' . $params['client_key'] . $params['douyin_id'] . $params['third_appid']);
        if (!empty($listdata)) {
            return ['err' => 0,'data' => json_decode($listdata, true)];
        }
        $token_url = 'https://developer.toutiao.com/api/apps/taskbox/query_task_video_daily_data/';
        //获取抖音token
        $arr = [
            'page_no' => $params['page'] ?? 0,
            'page_size' => $params['limit'] ?? 10000,
            'appid' => $appletData['app_id'],
            'access_token' => $token,
            'client_key' => isset($params['client_key']) ?trim($params['client_key']):'',//合作的撮合中介的网站应用key
            'douyin_id' => isset($params['douyin_id']) ?trim($params['douyin_id']):'',//主播抖音号
            'third_appid' => isset($params['third_appid']) ?trim($params['third_appid']):'',//第三方小程序appid（服务商使用的授权小程序）
        ];
        $cha = floor(($end_time - $start_time) / 86400);
        $billing_data = $params['start_time'];
        $list = [];
        $err=$m=0;
        $time_9=time() - (90 * 24 * 60 * 60);
        for($i = 0;$i <= $cha;$i++) {
            $start_time=strtotime($billing_data.'23:59:59');
            $end=$start_time-(30*3600*24);
            $arr['video_publish_start_time'] = $end<$time_9?$time_9:$end;//视频发布的起始时间，秒级时间戳
            $arr['video_publish_end_time'] =$start_time;//视频发布的结束时间，秒级时间戳
            $arr['billing_date'] = $billing_data;//计费日期
            $data = Common::curlRequest($token_url, 'POST', json_encode($arr));
            $data = json_decode($data, true); //获取token
            $num =$numtwo= 0;
            $name = $appletData['name'];
            $ClientName = '';
            if (isset($data['error'])&&$data['error'] == 0) {
                foreach($data['results'] as $key => $val) {
                    $gmv1d= $data['results'][$key]['BillingGMV1d'] / 100;
                    $num = round($num+$gmv1d, 2);
                    $gmv1dtwo= $data['results'][$key]['GMV1d'] / 100;
                    $numtwo = round($numtwo+$gmv1dtwo, 2);
                    $name = $data['results'][$key]['MicroAppTitle'];
                    $ClientName = $data['results'][$key]['ClientName'];
                }

            } else if(isset($data['error'])){
                $ClientName = $data['error'] . ":" . $data['message'];
                $err=1;
                $m++;
                if($m<10){
                    --$i;
                    continue;
                }
            }else{
                $ClientName ='请求错误';
                $err=1;
                $m++;
                if($m<10){
                    --$i;
                    continue;
                }
            }
            $m=0;
            $list[] = [
                'date' => $billing_data,
                'num' => $num,
                'numtwo'=>$numtwo,
                'name' => $name,
                'client_name' => $ClientName
            ];
            $billing_data = date("Y-m-d", strtotime($billing_data . " +1 day"));
            sleep(1);
        }
        if($err==0){
            $redis->set('douyin_data_video' . $appletData['id'] . '-' . strtotime($params['start_time'] . '00:00:00') . '-' . $end_time . '-' . $params['client_key'] . $params['douyin_id'] . $params['third_appid'], json_encode($list), 24*3600);
        }
        return ['err' => 0,'data' => $list];

    }

    /**
     * 查询任务台任务导出数据
     * @param $params 数据
     * page 页码
     * limit  条数
     * start_time 开始时间
     * end_time  结束时间
     * billing_date 计费时间
     * client_key  合作的撮合中介的网站应用key
     * douyin_id 主播抖音号
     * third_appid  第三方小程序appid（服务商使用的授权小程序）
     * return {"error": 0,"message": "SUCCESS","results": [ ]}
     * 请求地址文档：https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/server/promote/taskbox/query_task_video_data_daily
     */
    public function monthLeadingOut($params)
    {
        ini_set('memory_limit', '-1');
        ini_set('max_execution_time', 0);
        ob_end_clean();
        ob_start();
        $appletData = $this->getAppletInfo($params['id']);
        if(empty($appletData) || $appletData['type'] != 2) {
            return ['err' => 1,'msg' => '抖音账户错误'];
        }

        $token = $this->getAccessToken($params['id']);
        if($token == 0) {
            return  ['err' => 1,'msg' => '无法请求到抖音token'];
        }
        $start_time = strtotime($params['start_time'] . '00:00:00');
        $end_time = strtotime($params['end_time'] . '23:59:59');
        if($start_time < time() - (90 * 24 * 60 * 60)) {
            return ['err' => 1,'msg' => '搜索时间不能超出90天'];
        }
        // if(($end_time - $start_time) > (30 * 24 * 60 * 60)) {
        //     return ['err' => 1,'msg' => '搜索时间区间不能大于30天'];
        // }
        $arr = [
            'page_no' => $params['page'] ?? 0,
            'page_size' => $params['limit'] ?? 10000,
            'appid' => $appletData['app_id'],
            'access_token' => $token,
            // 'video_publish_start_time' => !empty($start_time) ? $start_time : strtotime(date('Y-m-d', time()) . '00:00:00'),//视频发布的起始时间，秒级时间戳
            // 'video_publish_end_time' => !empty($end_time) ? $end_time : strtotime(date('Y-m-d', time()) . '23:59:59'),//视频发布的结束时间，秒级时间戳
            // 'billing_date' => !empty($params['billing_date']) ? $params['billing_date'] : date('Y-m-d', time()),//计费日期
            'client_key' => isset($params['client_key']) ?trim($params['client_key']):'',//合作的撮合中介的网站应用key
            'douyin_id' => isset($params['douyin_id']) ?trim($params['douyin_id']):'',//主播抖音号
            'third_appid' => isset($params['third_appid']) ?trim($params['third_appid']):'',//第三方小程序appid（服务商使用的授权小程序）
        ];
        $token_url = 'https://developer.toutiao.com/api/apps/taskbox/query_task_video_daily_data/';
        $list = [];
        $time_9=time() - (90 * 24 * 60 * 60);
        if(!empty($params['billing_date'])) {
            $start_time=strtotime($params['billing_date'].'23:59:59');
            $end=$start_time-(30*3600*24);
            $arr['video_publish_start_time'] = $end<$time_9?$time_9:$end;//视频发布的起始时间，秒级时间戳
            $arr['video_publish_end_time'] =$start_time;//视频发布的结束时间，秒级时间戳
            $arr['billing_date'] = $params['billing_date'];//计费日期
            $data = Common::curlRequest($token_url, 'POST', json_encode($arr));
            $data = json_decode($data, true); //获取token
            if(isset($data['error'])&&$data['error'] == 0) {
                $list = $data['results'];
            }
        } else {
            $cha = floor(($end_time - $start_time) / 86400);
            $billing_data = $params['start_time'];
            for($i = 0;$i <= $cha;$i++) {
                $start_time=strtotime($billing_data.'23:59:59');
                $arr['video_publish_start_time'] = $start_time-(30*3600*24);//视频发布的起始时间，秒级时间戳
                $arr['video_publish_end_time'] =$start_time;//视频发布的结束时间，秒级时间戳
                $arr['billing_date'] = $billing_data;//计费日期
                $data = Common::curlRequest($token_url, 'POST', json_encode($arr));
                $data = json_decode($data, true); //获取token
                if(isset($data['error'])&&$data['error'] == 0) {
                    $list = array_merge($list, $data['results']);
                }
                $billing_data = date("Y-m-d", strtotime($billing_data . " +1 day"));
                sleep(2);
            }
        }
        if (!empty($list)) {
            $spreadsheet = new Spreadsheet();
            $worksheet = $spreadsheet->getActiveSheet();
            $worksheet->setCellValueByColumnAndRow(1, 1, '小程序名称');
            $worksheet->setCellValueByColumnAndRow(2, 1, '发布时间');
            $worksheet->setCellValueByColumnAndRow(3, 1, '任务ID');
            $worksheet->setCellValueByColumnAndRow(4, 1, '任务名');
            $worksheet->setCellValueByColumnAndRow(5, 1, '视频ID');
            $worksheet->setCellValueByColumnAndRow(6, 1, '作者');
            $worksheet->setCellValueByColumnAndRow(7, 1, '达人抖音ID');
            $worksheet->setCellValueByColumnAndRow(8, 1, '视频链接');
            $worksheet->setCellValueByColumnAndRow(9, 1, '视频标题');
            $worksheet->setCellValueByColumnAndRow(10, 1, '当日有效日活用户数');
            $worksheet->setCellValueByColumnAndRow(11, 1, '广告收入');
            $worksheet->setCellValueByColumnAndRow(12, 1, '当日交易金额(BillingGMV1d)');
            $worksheet->setCellValueByColumnAndRow(13, 1, '任务关联的当日退款金额');
            $worksheet->setCellValueByColumnAndRow(14, 1, '撮合中介名称');
            $worksheet->setCellValueByColumnAndRow(15, 1, '当日达人佣金');
            $worksheet->setCellValueByColumnAndRow(16, 1, 'feed流广告收入');
            $worksheet->setCellValueByColumnAndRow(17, 1, '当日视频交易金额(GMV1d)');
            $worksheet->setCellValueByColumnAndRow(18, 1, '当日退款金额');

            // 写入内容
            $line = 0;
            foreach ($list as $key => $item) {
                if(empty($item)) {
                    continue;
                }
                $line = $key + 2;
                $worksheet->setCellValueByColumnAndRow(1, $line, $item['MicroAppTitle']);
                $worksheet->setCellValueByColumnAndRow(2, $line, date('Y-m-d H:i:s',$item['PublishTime']));
                $worksheet->setCellValueExplicitByColumnAndRow(3, $line, $item['TaskId'], DataType::TYPE_STRING);
                $worksheet->setCellValueExplicitByColumnAndRow(4, $line, $item['TaskName'], DataType::TYPE_STRING);
                $worksheet->setCellValueExplicitByColumnAndRow(5, $line, $item['VideoId'], DataType::TYPE_STRING);
                $worksheet->setCellValueByColumnAndRow(6, $line, $item['Author']);
                $worksheet->setCellValueByColumnAndRow(7, $line, $item['DouyinID']);
                $worksheet->setCellValueByColumnAndRow(8, $line, $item['VideoLink']);
                $worksheet->setCellValueByColumnAndRow(9, $line, $item['VideoTitle']);
                $worksheet->setCellValueByColumnAndRow(10, $line, round($item['ActiveCnt1d']/ 100, 2));
                $worksheet->setCellValueByColumnAndRow(11, $line, round($item['AdShareCost1d']/ 100, 2));
                $worksheet->setCellValueByColumnAndRow(12, $line, round($item['BillingGMV1d']/ 100, 2));
                $worksheet->setCellValueByColumnAndRow(13, $line, round($item['BillingRefundGMV1d']/ 100, 2));
                $worksheet->setCellValueByColumnAndRow(14, $line, $item['ClientName']);
                $worksheet->setCellValueByColumnAndRow(15, $line, $item['ExpectedProfit']);
                $worksheet->setCellValueByColumnAndRow(16, $line, round($item['FeedAdShareCost1d']/ 100, 2));
                $worksheet->setCellValueByColumnAndRow(17, $line,  round($item['GMV1d']/ 100, 2));
                $worksheet->setCellValueByColumnAndRow(18, $line, round($item['RefundGMV1d']/ 100, 2));
            }

            $filename = './抖音任务台.xlsx';
            if (!empty($params['start_time']) && !empty($params['end_time'])) {
                $filename = $params['start_time'] . '-' . $params['end_time'] . '抖音任务台时间段.xlsx';
            }
            if (!empty($params['billing_date'])) {
                $filename = $params['billing_date'] . '抖音任务台收费时间.xlsx';
            }
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $filename . '"');
            header('Cache-Control: max-age=0');
            $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
            $writer->save('php://output');
            $spreadsheet->disconnectWorksheets();
            unset($spreadsheet);
            exit;
        }
    }

    //抖音通用支付退款回调
    public function newRefundCallback($params)
    {
        if ($params['type'] != 'refund') {
            return ['err_no' => 400, 'err_tips' => 'business fail'];
        }

        $orderInfo = json_decode($params['msg'], true);

        $orderNo = $orderInfo['out_refund_no'] ?? '';
        if (empty($orderNo)) return ['err_no' => 400, 'err_tips' => 'business fail'];

        $info = RefundRecord::where(['refund_no' => $orderNo])->find();

        if ($orderInfo['status'] != 'SUCCESS') {
            $saveData = [
                'status' => 2,
            ];
            if ($info){
                $info->save($saveData);
                $info->payRecord->save(['refund_status' => PayRecord::REFUND_STATUS_FAIL]);
            }
            return ['err_no' => 0, 'err_tips' => 'success'];
        }
        $saveData = [
            'refund_price' => round($orderInfo['refund_total_amount'] /100, 2),
            'refund_time' => date('Y-m-d H:i:s'),
            'status' => 1,
            'updated_at' => date('Y-m-d H:i:s'),
        ];
        if ($info){
            $info->save($saveData);
            $info->payRecord->save(['refund_status' => PayRecord::REFUND_STATUS_SUCC]);
        }
        return ['err_no' => 0, 'err_tips' => 'success'];
    }
}
